package gui.view;

import gui.controller.PropertyChangeConstants;
import gui.controller.SolveSupport;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * 
 * @author Felix Schliephacke
 * 
 * @param <T>
 */
public class SolutionInfo<T> extends JDialog implements PropertyChangeListener {

	private static final long serialVersionUID = -5049050157312511989L;

	private JPanel infoPanel;
	private JButton interrupt;
	private JLabel solutionLabel;
	private SolveSupport<T> solveSupport;
	private JPanel southPanel;

	public SolutionInfo(SolveSupport<T> solveSupport) {
		this.solveSupport = solveSupport;
		this.setTitle("Sudoku Solution Information");
		this.setSize(200, 200);
		this.setLayout(new BorderLayout());
		this.add(this.getSouthPanel(), BorderLayout.SOUTH);
		this.add(this.getInfoPanel(), BorderLayout.CENTER);
		this.setVisible(true);
	}

	@Override
	public void propertyChange(PropertyChangeEvent arg0) {
		if (arg0.getPropertyName().equals(
				PropertyChangeConstants.SOLUTIONS.toString())) {
			this.getSolutionLabel().setText(arg0.getNewValue().toString());
		}
	}

	private JPanel getInfoPanel() {
		if (this.infoPanel == null) {
			this.infoPanel = new JPanel();
			this.infoPanel.setLayout(new FlowLayout());
			this.infoPanel.add(new JLabel("Solutions:"));
			this.infoPanel.add(this.getSolutionLabel());
		}
		return this.infoPanel;
	}

	private JButton getInterruptButton() {
		if (this.interrupt == null) {
			this.interrupt = new JButton("Cancel");
			this.interrupt.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					SolutionInfo.this.getInterruptButton().setEnabled(false);
					SolutionInfo.this.solveSupport.interrupt();
				}
			});
		}
		return this.interrupt;
	}

	private JLabel getSolutionLabel() {
		if (this.solutionLabel == null) {
			this.solutionLabel = new JLabel("0");
		}
		return this.solutionLabel;
	}

	private JPanel getSouthPanel() {
		if (this.southPanel == null) {
			this.southPanel = new JPanel();
			this.southPanel.setLayout(new FlowLayout());
			this.southPanel.add(this.getInterruptButton());
		}
		return this.southPanel;
	}
}
